using System;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web;
using mojoPortal.Web.Editor;
using mojoPortal.Web.Framework;
using Resources;
using ud_Forum.Business;

namespace ud_Forum
{
    public partial class ForumEdit : NonCmsBasePage
	{
		private int moduleId = -1;
        private int itemId = -1;
        private String cacheDependencyKey;
        private Double timeOffset;

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            edContent.ProviderName = SiteUtils.GetEditorProviderName();
        }

        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            btnUpdate.Click += btnUpdate_Click;
            btnDelete.Click += btnDelete_Click;


            SiteUtils.SetupEditor(edContent, AllowSkinOverride, this);
        }

        #endregion

        private void Page_Load(object sender, EventArgs e)
		{
            if (!Request.IsAuthenticated)
            {
                SiteUtils.RedirectToLoginPage(this);
                return;
            }

            SecurityHelper.DisableBrowserCache();

            LoadSettings();

            
            if (!UserCanEditModule(moduleId, Forum.FeatureGuid))
			{
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

			PopulateLabels();

			if (!IsPostBack) 
			{
				if (itemId > -1)
				{
					PopulateControls();
					
				}
				else
				{
					ShowNewForumControls();
				}

                if ((Request.UrlReferrer != null) && (hdnReturnUrl.Value.Length == 0))
                {
                    hdnReturnUrl.Value = Request.UrlReferrer.ToString();
                    lnkCancel.NavigateUrl = hdnReturnUrl.Value;

                }
			}

            AnalyticsSection = ConfigHelper.GetStringProperty("AnalyticsForumSection", "forums");

		}

		private void PopulateLabels()
		{
            Title = SiteUtils.FormatPageTitle(siteSettings, ForumResources.ForumEditForumLabel);

            // TODO: implement
            divIsModerated.Visible = false;
            divIsActive.Visible = false;


            btnUpdate.Text = ForumResources.ForumEditUpdateButton;
            SiteUtils.SetButtonAccessKey(btnUpdate, ForumResources.ForumEditUpdateButtonAccessKey);

            lnkCancel.Text = ForumResources.ForumEditCancelButton;
            lnkCancel.NavigateUrl = SiteUtils.GetCurrentPageUrl();
            
            btnDelete.Text = ForumResources.ForumEditDeleteButton;
            SiteUtils.SetButtonAccessKey(btnDelete, ForumResources.ForumEditDeleteButtonAccessKey);
		}

		private void ShowNewForumControls()
		{
			btnDelete.Visible = false;
            btnUpdate.Text = ForumResources.ForumEditCreateButton;
			chkIsActive.Checked = true;
			txtSortOrder.Text = @"100";
			txtPostsPerPage.Text = @"10";
			txtThreadsPerPage.Text = @"40";
		}

		private void PopulateControls()
		{
			Forum forum = new Forum(itemId);

            if (forum.ModuleId != moduleId)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }
			
			lblCreatedDate.Text = forum.CreatedDate.AddHours(timeOffset).ToString();
            edContent.Text = forum.Description;
			txtTitle.Text = forum.Title;
			chkIsActive.Checked = forum.IsActive;
			chkAllowAnonymousPosts.Checked = forum.AllowAnonymousPosts;
			chkIsModerated.Checked = forum.IsModerated;
			txtSortOrder.Text = forum.SortOrder.ToString();
			txtPostsPerPage.Text = forum.PostsPerPage.ToString();
			txtThreadsPerPage.Text = forum.ThreadsPerPage.ToString();

			
		}


		private void btnUpdate_Click(object sender, EventArgs e)
		{
			Forum forum = new Forum(itemId);
            if ((forum.ItemId > -1)&&(forum.ModuleId != moduleId))
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }
			
            //SiteUser siteUser = new SiteUser(siteSettings, Context.User.Identity.Name);
            SiteUser siteUser = SiteUtils.GetCurrentSiteUser();
            if(siteUser != null)
			forum.CreatedByUserId = siteUser.UserId;

            forum.ModuleId = moduleId;
            forum.Description = edContent.Text;
			forum.Title = txtTitle.Text;
			forum.IsActive = chkIsActive.Checked;
			forum.AllowAnonymousPosts = chkAllowAnonymousPosts.Checked;
			forum.IsModerated = chkIsModerated.Checked;
			forum.SortOrder = int.Parse(txtSortOrder.Text);
			forum.PostsPerPage = int.Parse(txtPostsPerPage.Text);
			forum.ThreadsPerPage = int.Parse(txtThreadsPerPage.Text);

			if(forum.Save())
			{
                CurrentPage.UpdateLastModifiedTime();
                CacheHelper.TouchCacheDependencyFile(cacheDependencyKey);
                if (hdnReturnUrl.Value.Length > 0)
                {
                    WebUtils.SetupRedirect(this, hdnReturnUrl.Value);
                    return;
                }

                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());

			}
			
			
		}


		private void btnDelete_Click(object sender, EventArgs e)
		{
            Forum forum = new Forum(itemId);
            if (forum.ModuleId != moduleId)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            Forum.Delete(itemId);
            Forum.UpdateUserStats(-1); // updates all users
            CurrentPage.UpdateLastModifiedTime();

            if (hdnReturnUrl.Value.Length > 0)
            {
                WebUtils.SetupRedirect(this, hdnReturnUrl.Value);
                return;
            }

            WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());

		}

        private void LoadSettings()
        {
            WebUtils.GetApplicationRoot();
            moduleId = WebUtils.ParseInt32FromQueryString("mid", -1);
            itemId = WebUtils.ParseInt32FromQueryString("ItemID", -1);
            cacheDependencyKey = "Module-" + moduleId;
            timeOffset = SiteUtils.GetUserTimeOffset();
            edContent.WebEditor.ToolBar = ToolBar.FullWithTemplates;
            AddClassToBody("editforum");
        }
	}
}
